package com.medvalley.tcm.service.specification;

import com.medvalley.tcm.domain.SickInfo;
import com.medvalley.tcm.vo.inputvo.SickInfoSearchInputVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.text.ParseException;
import java.util.Date;

@Slf4j
public class SickInfoSpecification implements Specification<SickInfo> {

    private SickInfoSearchInputVo sickInfoSearchInputVo;

    public SickInfoSpecification(SickInfoSearchInputVo sickInfoSearchInputVo) {
        this.sickInfoSearchInputVo = sickInfoSearchInputVo;
    }

    @Override
    public Predicate toPredicate(Root<SickInfo> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
        String pattern = "yyyy-MM-dd HH:mm:ss";
        Predicate predicate = criteriaBuilder.conjunction();
        String beginDate = sickInfoSearchInputVo.getBeginDate();
        String endDate = sickInfoSearchInputVo.getEndDate();
        String sickName = sickInfoSearchInputVo.getSickName();
        String barCode = sickInfoSearchInputVo.getBarcode();


        if (!StringUtils.isEmpty(beginDate)) {
            try {
                Date begin = DateUtils.parseDate(beginDate + " 00:00:00", pattern);
                predicate.getExpressions().add(criteriaBuilder.greaterThan(root.get("createTime"), begin));
            } catch (ParseException e) {
                log.error("{} ", beginDate, e);
            }
        }
        if (!StringUtils.isEmpty(endDate)) {
            try {
                Date end = DateUtils.parseDate(endDate+ " 23:59:59", pattern);
                predicate.getExpressions().add(criteriaBuilder.lessThan(root.get("createTime"), end));
            } catch (ParseException e) {
                log.error("{} ", endDate, e);
            }
        }
        predicate.getExpressions().add(criteriaBuilder.equal(root.get("diagnosticMechanismID"), sickInfoSearchInputVo.getOrgId()));
        if (!StringUtils.isEmpty(sickName)) {
            predicate.getExpressions().add(criteriaBuilder.like(root.get("patientName"), "%" + sickInfoSearchInputVo.getSickName() + "%"));
        }
        if (!StringUtils.isEmpty(barCode)) {

            predicate.getExpressions().add(criteriaBuilder.like(root.get("barCode"), "%" + sickInfoSearchInputVo.getBarcode() + "%"));
        }
        return predicate;
    }
}
